package com.fili.gui.dialogs.config;

import com.fili.core.params.DryParams;
import gnu.io.CommPortIdentifier;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * Created by Claudiu-Florin FILIMON
 * Date: Oct 29, 2006
 * Time: 11:24:35 AM
 */
public class SerialConfigPanel extends JPanel
{
    private JComboBox cbPort;
    private JComboBox cbSpeed;
    private JComboBox cbBits;
    private JComboBox cbParity;
    private JComboBox cbStopBits;

    private Object[] serialPorts;


    public SerialConfigPanel()
    {
        setSize(153, 137);
        setLayout(null);

        enumeratePorts();

        JLabel lbl = new JLabel("Port");
        lbl.setBounds(8, 12, 49, 13);
        add(lbl);

        lbl = new JLabel("Viteza");
        lbl.setBounds(8, 36, 49, 13);
        add(lbl);

        lbl = new JLabel("Biti");
        lbl.setBounds(8, 60, 49, 13);
        add(lbl);

        lbl = new JLabel("Paritate");
        lbl.setBounds(8, 84, 49, 13);
        add(lbl);

        lbl = new JLabel("Biti stop");
        lbl.setBounds(8, 108, 49, 13);
        add(lbl);

        cbPort = new JComboBox(serialPorts);
        cbPort.setBounds(64, 8, 81, 21);
        add(cbPort);
        for (int i = 0; i < serialPorts.length; i++)
            if (serialPorts[i].equals(DryParams.getParams().getSerialPort()))
                cbPort.setSelectedIndex(i);

        cbSpeed = new JComboBox(new String[]{"2400"});
        cbSpeed.setBounds(64, 32, 81, 21);
        cbSpeed.setEnabled(false);
        add(cbSpeed);

        cbBits = new JComboBox(new String[]{"8"});
        cbBits.setBounds(64, 56, 81, 21);
        cbBits.setEnabled(false);
        add(cbBits);

        cbParity = new JComboBox(new String[]{"N"});
        cbParity.setBounds(64, 80, 81, 21);
        cbParity.setEnabled(false);
        add(cbParity);

        cbStopBits = new JComboBox(new String[]{"1"});
        cbStopBits.setBounds(64, 104, 81, 21);
        cbStopBits.setEnabled(false);
        add(cbStopBits);
    }

    private void enumeratePorts()
    {
        Enumeration portId = CommPortIdentifier.getPortIdentifiers();

        ArrayList<String> ports = new ArrayList<String>();

        while (portId.hasMoreElements())
        {
            CommPortIdentifier pid = (CommPortIdentifier) portId.nextElement();
            if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL)
            {
                ports.add(pid.getName());
                System.out.println(pid);
            }
        }

        serialPorts = ports.toArray();
        Arrays.sort(serialPorts);
    }

    public void saveParams()
    {
        if (cbPort.getSelectedItem() != null)
            DryParams.getParams().setSerialPort(cbPort.getSelectedItem().toString());
        else
            DryParams.getParams().setSerialPort("COM1");        
    }
}
